PARSER_MANAGER = {
    addDeleteHandler: function(){
        $('.delete-parser').click(function(){
            var $td = $(this).closest('td');
            $('#delete-confirmation-parser-fieldset-name').text($td.attr('data-fieldset-name'));
            $('#delete-confirmation input[name=id]').val($td.attr('data-parser-id'));
        });
    },

    addRunHandler: function(){
        $('.run-parser').click(function(){
            var $td = $(this).closest('td');
            $('#run-confirmation-parser-fieldset-name').text($td.attr('data-fieldset-name'));
            $('#run-confirmation input[name=id]').val($td.attr('data-parser-id'));
            if (parseInt($td.attr('data-progress')) > 0) {
                $('#run-confirmation .text-info').show();
            }
            else {
                $('#run-confirmation .text-info').hide();
            }
        });
    },

    addProgressUpdate: function(){
        setTimeout(function(){
            var args = arguments;
            $.ajax({
                url: '/parser/progress-update',
                type: 'get',
                error: genericError,
                success: function(res){
                    for (var i in res) {
                        var $parserRow = $('#parser-' + res[i].id);
                        if (res[i].progress == 100) {
                            $('.parser-progress', $parserRow).html('<a href="/parser/data/pid/' + res[i].id + '" class="label label-success">Done (click to see results)</a>');
                            $('a.run-parser', $parserRow).removeClass('hidden'); // Re-enable running
                            $('span.run-parser', $parserRow).addClass('hidden'); // the parser.
                        }
                        else {
                            $('.parser-progress', $parserRow).html('<span class="label label-info">Running (' + res[i].progress + '%)</span>');
                            $('a.run-parser', $parserRow).addClass('hidden');       // Disable running the parser
                            $('span.run-parser', $parserRow).removeClass('hidden'); // (we can't currently stop a parser in progress).
                        }
                    }
                    setTimeout(args.callee, 1000);
                }
            })
        });
    },

    init: function(){
        this.addDeleteHandler();
        this.addRunHandler();
        this.addProgressUpdate();
    }
}

$(function(){
    PARSER_MANAGER.init();
});